package com.yykj.hospital.server.service.from.template.impl;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalObjectUtil;
import com.yykj.hospital.server.model.entity.form.template.FormTrain;
import com.yykj.hospital.server.model.entity.form.template.FormTrainType;
import com.yykj.hospital.server.model.repository.form.template.FormTrainRepository;
import com.yykj.hospital.server.model.repository.form.template.FormTrainTypeRepository;
import com.yykj.hospital.server.service.from.template.FormTrainTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FormTrainTypeServiceImpl implements FormTrainTypeService {
    @Override
    public FormTrainType editFormTrainType(FormTrainType type) {

        FormTrainType formTrainType;
        if (type.getId() != null && type.getId() > 0) {
            formTrainType = trainTypeRepository.findById(type.getId()).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        } else {
            formTrainType = new FormTrainType();
        }
        LocalObjectUtil.copyNullValue(type, formTrainType);
        formTrainType = trainTypeRepository.save(formTrainType);

        return formTrainType;
    }

    @Override
    public void deleteFormTrainType(Integer id) {

        FormTrain formTrain = trainRepository.findFirstByTypeId(id);
        if (formTrain != null) {
            throw new NormalException(ResultEnums.TRAIN_TYPE_ERROR);
        }
        trainTypeRepository.deleteById(id);
    }

    @Override
    public List<FormTrainType> listFormTrainType(Integer hospitalId) {
        return  trainTypeRepository.findAllByHospitalIdOrderBySorting(hospitalId);
    }

    private FormTrainTypeRepository trainTypeRepository;

    private FormTrainRepository trainRepository;

    @Autowired
    public void setTrainTypeRepository(FormTrainTypeRepository trainTypeRepository) {
        this.trainTypeRepository = trainTypeRepository;
    }

    @Autowired
    public void setTrainRepository(FormTrainRepository trainRepository) {
        this.trainRepository = trainRepository;
    }
}
